/**
 * 
 */
package com.quanyan.place.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.TbBizPlaceOrderExample;
import com.quanyan.place.entity.TbBizPlaceOrderItem;
import com.quanyan.place.entity.TbBizPlaceOrderItemExample;
import com.quanyan.place.entity.TbBizPlacePayItem;
import com.quanyan.place.entity.TbBizPlacePrivateOrder;
import com.quanyan.place.entity.TbBizPlacePrivateOrderExample;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.mapper.PosUnionPayMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlacePayItemMapper;
import com.quanyan.place.mapper.TbBizPlacePrivateOrderMapper;
import com.quanyan.place.service.ApiPosUnionPayService;
import com.quanyan.place.service.PlaceGoodsService;
import com.quanyan.place.service.PlaceOrderService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.PlaceTicketService;

/**
 *银联pos商家端
 * @author tim
 * @time 2017年3月13日
 *
 */
@Service("posUnionPayService")
public class ApiPosUnionPayServiceImpl implements ApiPosUnionPayService {
	 @Autowired
	PosUnionPayMapper posUnionPayMapper;
	 
	 @Autowired
	TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
	 
	 @Autowired
	TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;
	 
	 @Autowired
	TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;
	 
	 @Autowired
	TbBizPlacePayItemMapper tbBizPlacePayItemMapper;
	 
	  @Autowired
	 PlaceOrderUtilService placeOrderUtilService;
	  
	  @Autowired
	  PlaceOrderService placeOrderService;

	  @Autowired
	 IBaseService iBaseService;
	  
	  @Autowired
	  PlaceTicketService placeTicketService;
	  
     @Autowired
     PlaceGoodsService placeGoodsService;
	/* (non-Javadoc)
	 */
	@Override
	@Transactional
	public int updatePosUnionOrderStatus(Integer uid, String orderNo, Date submitTime) {
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
		tbBizPlaceOrderExampleCriteria.andOrderNoEqualTo(orderNo);
		List<TbBizPlaceOrder> placeOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		Map paramsMap=new HashMap<>();
		paramsMap.put("uid", uid);
		paramsMap.put("submitTime", submitTime);
		paramsMap.put("orderNo", orderNo);
		if(!StringUtils.isEmpty(placeOrders)&&placeOrders.size()>0){
			return posUnionPayMapper.updatePosUnionOrderStatus(paramsMap);	
		}
		
		int result=posUnionPayMapper.updatePosUnionPrivateOrderStatus(paramsMap);
		if(result>0){
			TbBizPlacePrivateOrderExample tbBizPrivateOrderExample=new TbBizPlacePrivateOrderExample();
			TbBizPlacePrivateOrderExample.Criteria tbBizPrivateOrderExampleCriteria=tbBizPrivateOrderExample.createCriteria();
			tbBizPrivateOrderExampleCriteria.andOrderNoEqualTo(orderNo);
			List<TbBizPlacePrivateOrder> privateOrders=tbBizPlacePrivateOrderMapper.selectByExample(tbBizPrivateOrderExample);
			if(!StringUtils.isEmpty(privateOrders)&&privateOrders.size()>0){
				TbBizPlacePrivateOrder privateOrder=privateOrders.get(0);
				paramsMap.remove("orderNo");
				paramsMap.put("parentId", privateOrder.getParentId());
				return posUnionPayMapper.updatePosUnionOrderStatus(paramsMap);	
			}
		}
	  return 0;
	}

	

	@Override
	public List<String> selectPosUnionOrderNo(String orderNoSuffix, Integer uid,String isBookAll) {
		// TODO Auto-generated method stub
		Map<String, Object> paramsMap=new HashMap<>();
		paramsMap.put("orderNoSuffix", orderNoSuffix);
		paramsMap.put("uid", uid);
		if(isBookAll.equals(PlaceConstants.YES .toString())){
			return posUnionPayMapper.selectBookAllPosUnionOrderNo(paramsMap);
		}else{
			
			return posUnionPayMapper.selectPosUnionOrderNo(paramsMap);
		}
		
		
	}


	@Override
	public String getPosUnionPlaceOrderId(String orderNo) {
		// TODO Auto-generated method stub
		Map<String, Object> paramsMap=new HashMap<>();
		paramsMap.put("orderNo", orderNo);
		return posUnionPayMapper.getPosUnionPlaceOrderId(paramsMap);
	}



	@Override
	public String getPosUnionMemberOrderId(String orderNo) {
		// TODO Auto-generated method stub
		Map<String, Object> paramsMap=new HashMap<>();
		paramsMap.put("orderNo", orderNo);
		return posUnionPayMapper.getPosUnionMemberOrderId(paramsMap);
	}



	@Override
	public String getBookAllPlaceOrderId(String orderNo) {
		// TODO Auto-generated method stub
		Map<String, Object> paramsMap=new HashMap<>();
		paramsMap.put("orderNo", orderNo);
		return posUnionPayMapper.getBookAllPlaceOrderId(paramsMap);
	}


	@Override
	@Transactional
	public void updateInventoryStatus(String orderNo,String isBookAll) {
		// TODO Auto-generated method stub
		TbBizPlaceOrder tbBizPlaceOrder=null;
		List<TbBizPlaceOrderItem> tbBizPlaceOrderItems=new ArrayList<>();
		
		TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample=new TbBizPlaceOrderItemExample();
		TbBizPlaceOrderItemExample.Criteria tbBizPlaceOrderItemExampleCriteria = tbBizPlaceOrderItemExample.createCriteria();
		
		if(isBookAll.equals(PlaceConstants.YES.toString())){
			TbBizPlacePrivateOrderExample tbBizPrivateOrderExample=new TbBizPlacePrivateOrderExample();
			TbBizPlacePrivateOrderExample.Criteria tbBizPrivateOrderExampleCriteria=tbBizPrivateOrderExample.createCriteria();
			tbBizPrivateOrderExampleCriteria.andOrderNoEqualTo(orderNo);
			List<TbBizPlacePrivateOrder> privateOrders=tbBizPlacePrivateOrderMapper.selectByExample(tbBizPrivateOrderExample);
			
			if(!StringUtils.isEmpty(privateOrders)&&privateOrders.size()>0){
				TbBizPlacePrivateOrder	privateOrder=privateOrders.get(0);
				//查询子订单
				TbBizPlaceOrderExample tbBizPlaceOrderExamples = new TbBizPlaceOrderExample();
				TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriterias = tbBizPlaceOrderExamples.createCriteria();
				tbBizPlaceOrderExampleCriterias.andParentIdEqualTo(privateOrder.getId());
				  List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExamples);
		           
				  for (TbBizPlaceOrder placeOrd : tbBizPlaceOrders){
		                //查明细
						tbBizPlaceOrderItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrd.getPlaceOrderId());
						List<TbBizPlaceOrderItem> orderItems=tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
						if(orderItems!=null&&orderItems.size()>0){
							tbBizPlaceOrderItems.addAll(orderItems);
							BigDecimal receivedAmount=new BigDecimal(0);
							for(TbBizPlaceOrderItem orderItem:orderItems){
								
								receivedAmount=receivedAmount.add(this.handleDecimalNull(orderItem.getSalePrice()));
							}
							
							 //生成支付明细
						    TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
							tbBizPlacePayItem.setPlaceOrderId(placeOrd.getPlaceOrderId());
							tbBizPlacePayItem.setAmount(receivedAmount);
							tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
							tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY));
							tbBizPlacePayItem.setAdminPayType(23);
							tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);	
						}
						
		            }
				  
				  tbBizPlaceOrder=tbBizPlaceOrders.get(0);
				  tbBizPlaceOrder.setPlaceOrderId(privateOrder.getPlaceOrderId());//父订单转子订单
				 
			}
			
		}else{
			TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
			TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
			tbBizPlaceOrderExampleCriteria.andOrderNoEqualTo(orderNo);
			List<TbBizPlaceOrder> placeOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
			if(!StringUtils.isEmpty(placeOrders)&&placeOrders.size()>0){
				tbBizPlaceOrder=placeOrders.get(0);
				
				//查明细
				tbBizPlaceOrderItemExampleCriteria.andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
				List<TbBizPlaceOrderItem> orderItems = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
			    if(!StringUtils.isEmpty(orderItems)&&orderItems.size()>0){
			    	tbBizPlaceOrderItems.addAll(orderItems);
			    	 BigDecimal receivedAmount=new BigDecimal(0);
			    	 for(TbBizPlaceOrderItem orderItem:orderItems){
					    	receivedAmount=receivedAmount.add(this.handleDecimalNull(orderItem.getSalePrice()));
					  }
			    	 //生成支付明细
					    TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
						tbBizPlacePayItem.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
						tbBizPlacePayItem.setAmount(receivedAmount);
						tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
						tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY));
						tbBizPlacePayItem.setAdminPayType(23);
						tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);	
				   
			    }
			   
			    
			    //更新父订单状态
		        if (PlaceConstants.ORDER_USE_BLOCK_BOOKING == tbBizPlaceOrder.getUseType()) {
		        	placeOrderService.checkBlockOrder(tbBizPlaceOrder, PlaceConstants.ORDER_PAYED_STATUS, null);
		        }
		        
			}
			
		}
		
		
		if(!StringUtils.isEmpty(tbBizPlaceOrder)&&(!StringUtils.isEmpty(tbBizPlaceOrderItems)&&tbBizPlaceOrderItems.size()>0)){
			
			List<TbBizPlaceOrderItem> placeUnitOrderItemList=new ArrayList<>();
			List<TbBizPlaceOrderItem> placeTicketOrderItemList=new ArrayList<>();
			List<TbBizPlaceOrderItem> placeGoodsOrderItemList=new ArrayList<>();
			 BigDecimal receivedAmount=new BigDecimal(0);
			for(TbBizPlaceOrderItem orderItem:tbBizPlaceOrderItems){
				receivedAmount=receivedAmount.add(this.handleDecimalNull(orderItem.getSalePrice()));
				if (orderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)) {// 门票
					placeTicketOrderItemList.add(orderItem);
				} else if (orderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
						|| orderItem.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)) {// 开单包场
			        placeUnitOrderItemList.add(orderItem);
				} else if (orderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)) {// 小商品
					placeGoodsOrderItemList.add(orderItem);
				}	
			}
			
				//改变库存
				 if (!org.springframework.util.CollectionUtils.isEmpty(placeUnitOrderItemList)){
		                //减场地库存
		                try {
		                    iBaseService.placeBillingUpdatePlaceUnitSalePlan(placeUnitOrderItemList,PlaceConstants.PLACE_ORDER_STATUS);
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
		          if (!org.springframework.util.CollectionUtils.isEmpty(placeTicketOrderItemList)){
		                //修改门票统计
		                try {
		                    placeTicketService.ticketStatisticsForScanPay(tbBizPlaceOrder.getPlaceId(),placeTicketOrderItemList);
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
		           if (!org.springframework.util.CollectionUtils.isEmpty(placeGoodsOrderItemList)){
		                //减商品库存
		                try {
		                    placeGoodsService.updateGoodsInventory(placeGoodsOrderItemList,tbBizPlaceOrder);
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
				  
				 //产生支付流水
		        ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(tbBizPlaceOrder,receivedAmount,(byte)0,(byte)0);
		        try {
		            placeOrderUtilService.insertOrderHistory(reqOrderHistory);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		}
		
		
		
	}
	private  BigDecimal handleDecimalNull(BigDecimal t){
		if(t==null){
			return new BigDecimal(0.0);
		}
		return t;
	}
}
